const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const bcrypt = require('bcrypt');

const UserSchema = new Schema({
  name: {
    type: String,
    minlength: [4, '用户名不能少于4位'],
    maxlength: [12, '用户名不能大于12位'],
    unique: true, // 不可重复约束
    required: true // 不可为空约束
  },
  password: {
    type: String,
    required: true
  },
  email: {
    type: String,
    required: true,
    unique: true
  },
  signature: {
    type: String,
    default: 'null'
  },
  avatar: {
    type: String
  },
  integral: {
    type: Number,
    default: 0
  },
  loginIp: {
    type: String
  },
  isAdmin: {
    type: Boolean,
    default: false
  },
  state: {
    type: Boolean,
    default: true
  },
  createAt: {
    type: Date,
    default: Date.now()
  },
  createTimeStr: {
    type: String,
    default: new Date().getTime()
  },
  updateAt: {
    type: Date
  },
  token: {
    type: String
  },
  topicCount: { type: Number, default: 0 },
  replyCount: { type: Number, default: 0 },
  followers: { type: Number, default: 0 }
});

// 添加用户保存时中间件对password进行bcrypt加密,这样保证用户密码只有用户本人知道
UserSchema.pre('save', function (next) {
  let user = this;
  user.updateAt = new Date();
  if (this.isModified('password') || this.isNew) {
    bcrypt.genSalt(10, function (err, salt) {
      if (err) {
        return next(err);
      }
      bcrypt.hash(user.password, salt, function (err, hash) {
        if (err) {
          return next(err);
        }
        user.password = hash;
        next();
      });
    });
  } else {
    return next();
  }
});
// 校验用户输入密码是否正确
UserSchema.methods.comparePassword = function (passw, cb) {
  bcrypt.compare(passw, this.password, (err, isMatch) => {
    if (err) {
      return cb(err);
    }
    cb(null, isMatch);
  });
};

module.exports = mongoose.model('User', UserSchema);
